package com.shawn.baseappbygroovydsl.ui.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator
import com.shawn.baseappbygroovydsl.R
import kotlin.math.tan

class StripedProgressBar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val progressPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val progressRect = RectF()
    private var progressBitmap: Bitmap? = null

    // 动画相关变量
    private var stripeOffset = 0f
    private val animator = ValueAnimator.ofFloat(0f, 1f).apply {
        repeatCount = ValueAnimator.INFINITE
        duration = 300L // 动画持续时间，可调整
        interpolator = LinearInterpolator()
    }

    // 条纹动画方向枚举
    enum class StripeAnimationDirection {
        LEFT_TO_RIGHT, RIGHT_TO_LEFT
    }
    // 条纹动画方向，默认为从左往右
    private var stripeAnimationDirection = StripeAnimationDirection.RIGHT_TO_LEFT
    // 条纹参数
    private val stripeWidth = 20f // 条纹宽度，可调整
    private val stripeAngle = 45f // 条纹倾斜角度，可调整
    private val stripeColor = Color.WHITE // 条纹颜色，可调整
    private val stripeAlpha = 128 // 条纹透明度，可调整 (0-255)
    // 渐变色相关变量
    private var gradientStartColor = Color.BLUE
    private var gradientEndColor = Color.CYAN
    private var gradientOrientation = GradientOrientation.LEFT_TO_RIGHT
    enum class GradientOrientation {
        LEFT_TO_RIGHT, TOP_TO_BOTTOM, TR_BL, TL_BR
    }

    // 最大值，默认为 100
    var max = 100
        set(value) {
            field = if (value > 0) value else 1
            invalidate()
        }

    // 当前进度值
    var progress = 0
        set(value) {
            field = value.coerceIn(0, max)
            invalidate()
        }

    var cornerRadius = 0f // 圆角半径

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.StripedProgressBar)
        try {
            backgroundPaint.color = typedArray.getColor(
                R.styleable.StripedProgressBar_backgroundColor,
                Color.LTGRAY
            )

            val bitmapResId = typedArray.getResourceId(R.styleable.StripedProgressBar_progressImage, 0)
            if (bitmapResId != 0) {
                progressBitmap = BitmapFactory.decodeResource(context.resources, bitmapResId)
            }

            progress = typedArray.getInt(R.styleable.StripedProgressBar_progress, 0)
            max = typedArray.getInt(R.styleable.StripedProgressBar_max, 100)
            cornerRadius = typedArray.getDimension(R.styleable.StripedProgressBar_cornerRadius, 0f)

            // 读取条纹动画方向
            stripeAnimationDirection = when (typedArray.getInt(
                R.styleable.StripedProgressBar_stripeAnimationDirection,
                0
            )) {
                1 -> StripeAnimationDirection.RIGHT_TO_LEFT
                else -> StripeAnimationDirection.LEFT_TO_RIGHT
            }
            // 修改动画更新逻辑
            animator.addUpdateListener {
                val animatedValue = it.animatedValue as Float
                stripeOffset = if (stripeAnimationDirection == StripeAnimationDirection.LEFT_TO_RIGHT) {
                    (1 - animatedValue) * stripeWidth * 2
                } else {
                    animatedValue * stripeWidth * 2
                }
                invalidate()
            }
            // 添加渐变色属性读取
            gradientStartColor = typedArray.getColor(
                R.styleable.StripedProgressBar_gradientStartColor,
                Color.BLUE
            )
            gradientEndColor = typedArray.getColor(
                R.styleable.StripedProgressBar_gradientEndColor,
                Color.CYAN
            )
            gradientOrientation = when (typedArray.getInt(
                R.styleable.StripedProgressBar_gradientOrientation,
                0
            )) {
                1 -> GradientOrientation.TOP_TO_BOTTOM
                2 -> GradientOrientation.TR_BL
                3 -> GradientOrientation.TL_BR
                else -> GradientOrientation.LEFT_TO_RIGHT
            }
        } finally {
            typedArray.recycle()
        }

        // 初始化进度绘制
        progressPaint.style = Paint.Style.FILL
        progressPaint.color = Color.BLUE // 默认进度颜色，会被图片覆盖
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        animator.start()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        animator.cancel()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val width = width.toFloat()
        val height = height.toFloat()

        // 绘制背景圆角矩形
        canvas.drawRoundRect(0f, 0f, width, height, cornerRadius, cornerRadius, backgroundPaint)

        // 绘制进度区域
        val progressWidth = width * progress / max
        progressRect.set(0f, 0f, progressWidth, height)

        // 保存画布状态以应用裁剪
        canvas.save()

        // 裁剪画布为进度区域，确保条纹不会超出进度范围
        canvas.clipRect(progressRect)

        // 如果有进度图片，使用图片绘制
        progressBitmap?.let { bitmap ->
            val bitmapShader = BitmapShader(bitmap, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT)
            progressPaint.shader = bitmapShader
            canvas.drawRoundRect(progressRect, cornerRadius, cornerRadius, progressPaint)
        } ?: run {
            // 如果没有图片，使用纯色绘制进度背景
            val gradient = createGradient(progressRect)
            progressPaint.shader = gradient
            //progressPaint.color = Color.BLUE // 默认进度颜色
            canvas.drawRoundRect(progressRect, cornerRadius, cornerRadius, progressPaint)

            // 绘制平行四边形条纹
            drawStripes(canvas, progressRect)
        }

        // 恢复画布状态
        canvas.restore()
    }

    private fun drawStripes(canvas: Canvas, rect: RectF) {
        val stripePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
            color = stripeColor
            alpha = stripeAlpha
        }

        val stripeHeight = rect.height()
        val tan = tan(Math.toRadians(stripeAngle.toDouble())).toFloat()
        val stripeLength = stripeHeight / tan

        // 计算需要绘制的条纹数量
        val stripeCount = (rect.width() / (stripeWidth + stripeLength) + 2).toInt()

        // 绘制条纹
        for (i in -1 until stripeCount) {
            val startX = i * (stripeWidth + stripeLength) - stripeOffset

            val path = Path().apply {
                moveTo(startX, rect.top)
                lineTo(startX + stripeLength, rect.bottom)
                lineTo(startX + stripeLength + stripeWidth, rect.bottom)
                lineTo(startX + stripeWidth, rect.top)
                close()
            }

            canvas.drawPath(path, stripePaint)
        }
    }

    private fun createGradient(rect: RectF): LinearGradient {
        return when (gradientOrientation) {
            GradientOrientation.LEFT_TO_RIGHT -> LinearGradient(
                rect.left, rect.centerY(),
                rect.right, rect.centerY(),
                gradientStartColor, gradientEndColor,
                Shader.TileMode.CLAMP
            )
            GradientOrientation.TOP_TO_BOTTOM -> LinearGradient(
                rect.centerX(), rect.top,
                rect.centerX(), rect.bottom,
                gradientStartColor, gradientEndColor,
                Shader.TileMode.CLAMP
            )
            GradientOrientation.TR_BL -> LinearGradient(
                rect.right, rect.top,
                rect.left, rect.bottom,
                gradientStartColor, gradientEndColor,
                Shader.TileMode.CLAMP
            )
            GradientOrientation.TL_BR -> LinearGradient(
                rect.left, rect.top,
                rect.right, rect.bottom,
                gradientStartColor, gradientEndColor,
                Shader.TileMode.CLAMP
            )
        }
    }
}


